package com.dxd.onlineshop.service.impl;

import com.dxd.onlineshop.mapper.LoginMapper;
import com.dxd.onlineshop.pojo.User;
import com.dxd.onlineshop.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public User login(String account, String password) {
        return loginMapper.login(account, password);
    }

    @Override
    public User register(User user) throws Exception {
        if (checkAccountExists(user.getAccount())) {
            throw new Exception("该邮箱已被注册");
        }
        if (checkUsernameExists(user.getUsername())) {
            throw new Exception("该用户名已被使用");
        }

        user.setRole(0); // 设置为普通用户
        user.setCreatedAt(LocalDateTime.now());
        user.setBalance(0); // 初始余额为0

        int result = loginMapper.register(user);
        if (result > 0) {
            return loginMapper.getUserById(user.getId());
        } else {
            throw new Exception("注册失败");
        }
    }

    @Override
    public boolean checkAccountExists(String account) {
        return loginMapper.checkAccountExists(account) > 0;
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return loginMapper.checkUsernameExists(username) > 0;
    }
}